<script setup>
import { Plus, Search, Document, Delete, More, Edit, Refresh, EditPen, View, InfoFilled, Share, Lock, CollectionTag } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, tagEmits, tagProps } from 'element-plus';
import { reactive, ref, onMounted } from 'vue';
import {get, post, del, put, formPost} from '../api/http'

const noteList = reactive([])
const note = reactive({})
const keyword = ref('')
const showAddNote = ref(false)
const text = ref('> 你还没有任何笔记，快创建一篇吧，笔记可以设置为公共的，这样你的笔记就会出现在博客中，当然也可以设为私密的。\n 左侧的列表针对创建的笔记支持右键菜单操作，右键有如下功能:\n > - 编辑 \n > - 重命名\n > - 设为About页\n > - 公开内容\n > - 设为私有\n > - 设置标签\n > - 删除\n')
const currentNoteId = ref(0)
const showRightMenu = ref(false)
const selectForRight = reactive({})
const isAddNote = ref(true)
const isPreview = ref(true)
const loading = ref(false)
const tagList = ref([])
const showSetTagDialog = ref(false)
const selectedTagId = ref([])
const noteDescribe = ref('')
const showSetDescribeDialog = ref(false)
const showAddNoteSuccess = ref(false)

const getNoteList = () => {
    loading.value = true
    get('note',{'keyword':keyword.value}).then(res=>{
        if(res.status){
            noteList.value = res.data.list;
            if(res.data.list.length>0){
                selectedNote(res.data.list[0].id)
            }
        }else{
            ElMessage({message:res.msg,type:res.status?'success':'error'})
        }
        loading.value = false
    })
}


const addNote = () => {
    if(isAddNote.value){
        post('note',note).then(res=>{
            ElMessage({message:res.msg,type:res.status?'success':'error'})
            if(res.status){
                showAddNote.value = false;
                getNoteList()
                showAddNoteSuccess.value = true
            }
        })
    }else{
        put('note',note).then(res=>{
            ElMessage({message:res.msg,type:res.status?'success':'error'})
            if(res.status){
                showAddNote.value = false;
                getNoteList()   
            }
        })
    }
    
}

const removeNote = (id) => {
    ElMessageBox.confirm('该操作将永久删除此笔记，是否删除？','提示',{type:'warning'}).then(()=>{
        del('note',[id]).then(res=>{
            ElMessage({message:res.msg,type:res.status?'success':'error'})
        if(res.status){
            getNoteList()
        }
        })
    })
}

const saveText = () => {
    post('note/text',{id:currentNoteId.value,content:text.value}).then(res=>{
        ElMessage({message:res.msg,type:res.status?'success':'error'})
    })
}

const selectedNote = (id) => {
    loading.value = true
    currentNoteId.value = id;
    isPreview.value = true;
    get('note/text',{id:id}).then(res=>{
        text.value = res.data;
        loading.value = false
    })
}

const clickRightEvent = (e,data) => {
    // selectedNote(data.id)
    selectForRight.value = data;
    let tempIds = []
    data.noteTagList.forEach(tag => {
        tempIds.push(tag.id)
    });
    selectedTagId.value = tempIds;
    let rightMenu = document.getElementById('rightMenu');  
    rightMenu.style.left = e.clientX+"px";
    rightMenu.style.top = e.clientY+"px";
    showRightMenu.value = true;
}

const rename = () => {
    note.noteTitle = selectForRight.value.noteTitle;
    note.id = selectForRight.value.id;
    showAddNote.value = true;
    isAddNote.value = (false);
}

const deleteByRight = () => {
    removeNote(selectForRight.value.id)
}

const changeEditorModel = () => {
    isPreview.value = !isPreview.value
    showAddNoteSuccess.value = false
}

const globalClick = () => {
    showRightMenu.value = false;
}

const setAbout = () => {
    note.viewType = 'about';
    note.id = selectForRight.value.id;
    put('note/viewType',note).then(res=>{
        ElMessage({message:res.msg,type:res.status?'success':'error'})
        if(res.status){
            showAddNote.value = false;
        }
    })
}

const shareNote = () => {
    note.viewStatus = 'public';
    note.noteDescribe = noteDescribe.value
    note.id = selectForRight.value.id;
    put('note',note).then(res=>{
        ElMessage({message:res.msg,type:res.status?'success':'error'})
        if(res.status){
            showAddNote.value = false;
            showSetDescribeDialog.value = false;
        }
    })
}

const setTagForNote = () => {
    let tempTagList = []
    selectedTagId.value.forEach(tagId => {
        let obj = tagList.value.find((value)=>{
            return value.id == tagId
        })
        tempTagList.push(obj)
    });
    note.noteTagList = tempTagList;
    
    note.id = selectForRight.value.id;
    put('note',note).then(res=>{
        ElMessage({message:res.msg,type:res.status?'success':'error'})
        if(res.status){
            showSetTagDialog.value = false;
        }
    })
}

const privateNote = () => {
    note.viewStatus = 'private';
    
    note.id = selectForRight.value.id;
    put('note',note).then(res=>{
        ElMessage({message:res.msg,type:res.status?'success':'error'})
        if(res.status){
            showAddNote.value = false;
        }
    })
}

const getTagList = () => {
    get('tag').then(res=>{
        tagList.value = res.data.list
    })
}

const handleTagChange = (id) => {
}

const getDescribeFromText = () => {
    noteDescribe.value = text.value.substring(0,100)
}

const preSetDescribe = () => {
    noteDescribe.value = ''
    noteDescribe.value = selectForRight.value.noteDescribe
    showSetDescribeDialog.value=true
}

const handleUploadImage = (event, insertImage, files) => {
    let param = new FormData();
    param.append("file",files[0])
    formPost('file/blog', param).then(res=>{
        if(res.status){
            // 此处只做示例
            insertImage({
                url: res.data,
                desc: files[0].fileName,
                // width: 'auto',
                // height: 'auto',
            });
        }else{
            ElMessage({type:'error',message:res.msg})
        }
    })
}



onMounted(()=>{
    getNoteList()
})

</script>
<template>
    <main v-blog-title data-title="在线笔记" @click="globalClick" v-loading="loading">
        <div class="rightMenu" id="rightMenu" v-show="showRightMenu">
            <ul>
                <li v-if="isPreview" @click="changeEditorModel"><el-icon style="padding-right: 5px;"><EditPen/></el-icon>编辑</li>
                <li v-if="!isPreview" @click="changeEditorModel"><el-icon style="padding-right: 5px;"><View/></el-icon>预览</li>
                <li @click="rename"><el-icon style="padding-right: 5px;"><Refresh/></el-icon>重命名</li>
                <li @click="setAbout"><el-icon style="padding-right: 5px;"><InfoFilled/></el-icon>设为About页</li>
                <li @click="preSetDescribe"><el-icon style="padding-right: 5px;"><Share/></el-icon>公开内容</li>
                <li @click="privateNote"><el-icon style="padding-right: 5px;"><Lock/></el-icon>设为私有</li>
                <li @click="showSetTagDialog=true;getTagList();"><el-icon style="padding-right: 5px;"><CollectionTag/></el-icon>设置标签</li>
                <li @click="deleteByRight" style="color: red;"><el-icon style="padding-right: 5px;"><Delete/></el-icon>删除</li>
            </ul>
        </div>
        <el-row>
            <el-col :span="5">
                <div class="note-list">
                    <div class="note-option">
                        <el-input @input="getNoteList" v-model="keyword" placeholder="关键字搜索" style="margin: 10px;" :prefix-icon="Search"></el-input>
                        <el-button @click="showAddNote=true;isAddNote=true" type="primary" style="margin-right: 10px;">创建</el-button>
                    </div>
                    <div class="note-item" v-for="item in noteList.value" :key="item.id">
                        <div class="note-main" :style="currentNoteId === item.id ? 'background-color:var(--el-color-primary); color:#fff;' : ''" @click="selectedNote(item.id)" @contextmenu.prevent="clickRightEvent($event,item)">
                            <div class="left">
                                <!-- <el-icon style="padding:10px 5px; width: 20px;"><Document /></el-icon> -->
                                <span class="note-title">{{ item.noteTitle }}</span>
                                <div class="note-sub">
                                    <span>{{ item.createTime }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-col>
            <el-col :span="19">
                <div class="note-preview">
                    <!-- <el-empty description="暂无笔记内容" :image-size="200"></el-empty> -->
                    <v-md-editor @blur="saveText" placeholder="输入笔记内容" :disabled-menus="[]" left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | save | emoji" @upload-image="handleUploadImage" v-if="!isPreview" @save="saveText" v-model="text"></v-md-editor>
                    <v-md-preview v-if="isPreview" :text="text"></v-md-preview>
                </div>
            </el-col>
        </el-row>
        <el-dialog width="40%" title="笔记信息" v-model="showAddNote">
            <el-form>
                <el-form-item label="">
                    <el-input v-model="note.noteTitle" placeholder="笔记标题"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-input type="textarea" v-model="note.noteDescribe" resize="none" placeholder="笔记描述"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button style="width: 100%;" type="primary" @click="addNote">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-dialog v-model="showSetTagDialog" title="标签信息">
            <el-form>
                <el-form-item v-model="showSetTagDialog">
                    <el-select @change="handleTagChange" v-model="selectedTagId" placeholder="选择标签" style="width:100%;" multiple>
                        <el-option v-for="item in tagList" :key="item.id" :label="item.tagName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <div style="width:100%; text-align:right;">
                    <el-button @click="setTagForNote" type="primary">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog title="笔记描述" v-model="showSetDescribeDialog">
            <el-input v-model="noteDescribe" type="textarea" resize="none" rows="5" placeholder="输入笔记描述" maxlength="200" show-word-limit></el-input>
            <div class="optionBtn">
                <!-- <el-button @click="getDescribeFromText">一键提取</el-button> -->
                <el-button type="primary" @click="shareNote">公开博文</el-button>
            </div>
        </el-dialog>
        <el-dialog title="新增成功" v-model="showAddNoteSuccess" :close-on-click-modal="false">
            <div style="color: red;">新增笔记成功，后续可以<b>右键左侧笔记标题</b>进行编辑、重命名等操作.如下图：</div>
            <img src="https://www.huhailong.vip/res/img/blog/note_right.png" style="width: 100%;" />
            <div style="margin-top:20px; text-align: right;">
                <el-button @click="showAddNoteSuccess=false" type="info">稍后编辑</el-button>
                <el-button @click="changeEditorModel" type="primary">进入编辑</el-button>
            </div>
        </el-dialog>
    </main>
</template>
<style scoped>
.note-list{
    height: calc(100vh - 60px);
    border-right: 1px solid #aaa;
    background-color: #fff;
    overflow-y: auto;
}
.note-preview{
    width: 100%;
    background-color: #fff;
    height: calc(100vh - 60px);
}
.note-option{
    display: flex;
    align-items: center;
    background-color: #fff;
}
.note-item{
    display: flex;
    flex-direction: column;
    justify-content: center;
    /* align-items: center; */
    font-size: 14px;
    background-color: #fff;
    margin: 5px 0;
}
.note-main{
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
    cursor: pointer;
}
.note-sub{
    font-size: 12px;
    padding: 5px 0;
    color: #aaa;
}
.note-title{
    cursor: pointer;
    font-size: 16px;
}
.note-item:hover{
    background-color: var(--el-color-primary);
    color: #fff;
}
.note-main > .right{
    display: flex;
    align-items: center;
}
.note-preview:deep(.v-md-editor){
    height: 100%;
}
.rightMenu{
    width: 200px;
    position: absolute;
    z-index: 1000;
    background-color: var(--el-color-primary);
    color: #fff;
    border-radius: 5px;
    padding: 10px;
}
.rightMenu > ul{
    margin: 0;
    padding: 0;
}
.rightMenu > ul > li{
    list-style: none;
    cursor: pointer;
    padding: 5px;
    display: flex;
    align-items: center;
    border-radius: 5px;
}
.rightMenu > ul > li:hover{
    background-color: var(--el-color-primary);
}
.note-preview{
    overflow-y: auto;
}
.optionBtn{
    margin-top: 10px;
}
</style>